var MongoClient = require('mongodb').MongoClient;

var jwt = require('jsonwebtoken');

var response = require('./response');

var Url = "mongodb://localhost:27017/demo";


var Table = 'users';

var ChaterListTable = 'chaterlist';

var user = {};


var dbErrorMsg = "数据库连接失败";


function connect(callback) {

    MongoClient.connect(Url, function (err, db) {

        if (err) {
            response.error(res, err, dbErrorMsg);
        } else {
            callback(db);
        }
    });
}


user.getUsers = function (res) {

    connect(function (db) {

        db.collection(Table).find({}).toArray(function (err, result) {


            if (err) {
                response.error(res, err, '获取用户列表失败');
            } else {
                response.success(res, result);
            }
            db.close();
        });

    });

};

// sign up
user.addUser = function (_user, res) {


    connect(function (db) {

        console.log({ username: _user.username });

        _user.createtime = new Date().getTime();

        db.collection(Table).find({ username: _user.username }).toArray(function (err, result) {

            if (err) {
                response.error(res, err, '用户获取失败');
            } else {

                console.log(result);


                if (result.length > 0) {
                    response.error(res, result, '该用户已经注册');
                }

                db.collection(Table).insertOne(_user, function (err, result) {


                    if (err) {
                        response.error(res, err, '用户注册失败');
                    } else {
                        response.success(res, result);
                    }
                    db.close();

                });
            }

        });


    });

};

user.delUser = function (_user, res) {
    connect(function (db) {

        db.collection(Table).deleteOne(_user, function (err, result) {

            if (err) {
                response.error(res, err, '用户删除失败');
            } else {
                response.success(res, result);
            }
            db.close();
        });


    });

};

user.getUserInfo = function (_user, res) {
    connect(function (db) {

        db.collection(Table).find(_user, function (err, result) {

            if (err) {
                response.error(res, err, '用户获取失败');
            } else {
                response.success(res, result);
            }
            db.close();
        });


    });
};


user.updateUser = function (_user, res) {
    connect(function (db) {

        db.collection(Table).find(_user, _user, function (err, result) {



            if (err) {
                response.error(res, err, '用户更新失败');
            } else {
                response.success(res, result);
            }
            db.close();
        });


    });
};

user.login = function (_user, res) {

    connect(function (db) {

        console.log({ username: _user.username });



        db.collection(Table).find({ username: _user.username }).toArray(function (err, result) {

            if (err) {
                response.error(res, err, '用户获取失败');
            } else {

                console.log(result);


                if (result.length > 0) {

                    let _data = result[0];

                    if (_data.password === _user.password) {

                        let myToken = jwt.sign({
                            exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 7),
                            data: _user
                        }, 'zyc');

                        console.log(myToken);

                        res.cookie('token', myToken);

                        res.append('token', myToken);

                        response.success(res, _data);

                    } else {
                        response.error(res, _data, '用户密码错误');
                    }


                } else {

                    response.error(res, result, '该用户未注册');

                }


            }

            db.close();

        });


    });
};

// 添加好友申请
user.addFriendRequest = function (_friendName, res) {
    connect(function (db) {

        console.log({ username: _username });

        let _query = { '$regex': _username, '$options': 'i' };

        db.collection('users').find({ "username": _query }).toArray(function (err, result) {

            if (err) {
                callback({ success: false, error: '查询异常', msg: '查询异常' });
            } else {

                console.log(result);

                let temp = [];

                for (let i = 0; i < result.length; i++) {

                    let item = result[i];
                    temp.push({
                        username: item.username,
                        _id: item._id
                    });
                }

                callback({ success: true, data: temp });
            }

            db.close();

        });

    });
};

// socket
user.getChaterlist = function (_user, callback) {

    connect(function (db) {

        console.log({ userid: _user._id });

        db.collection(ChaterListTable).find({ "userid": _user._id }).toArray(function (err, result) {

            if (err) {
                callback({ success: false, error: '查询异常', msg: '查询异常' });
            } else {

                console.log(result);

                callback({ success: true, data: result });
            }

            db.close();

        });


    });
};

user.getChaterFriends = function (_user, callback) {

    connect(function (db) {

        console.log({ userid: _user._id });

        db.collection('friends').find({ "userid": _user._id }).toArray(function (err, result) {

            if (err) {
                callback({ success: false, error: '查询异常', msg: '查询异常' });
            } else {

                console.log(result);

                callback({ success: true, data: result });
            }

            db.close();

        });

    });
};


user.searchFriends = function (_username, callback) {

    connect(function (db) {

        console.log({ username: _username });

        let _query = { '$regex': _username, '$options': 'i' };

        db.collection('users').find({ "username": _query }).toArray(function (err, result) {

            if (err) {
                callback({ success: false, error: '查询异常', msg: '查询异常' });
            } else {

                console.log(result);

                let temp = [];

                for (let i = 0; i < result.length; i++) {

                    let item = result[i];
                    temp.push({
                        username: item.username,
                        _id: item._id
                    });
                }

                callback({ success: true, data: temp });
            }

            db.close();

        });

    });
};


user.addFriends = function (obj, callback) {

    var friend = obj.friend;

    var user = obj.user;

    connect(function (db) {

        console.log({ username: friend.username });

        friend.createtime = new Date().getTime();


        db.collection('friends').find({ "userid": user._id }).toArray(function (err, result) {

            if (err) {
                callback({ success: false, error: '插入frinds表失败', msg: '添加好友失败' });
            } else {

                console.log(result);

                // 已经有过档案arry
                if (result.length > 0) {

                    let _updateList = result[0].list;

                    console.log(_updateList);

                    _updateList.push(friend);
                    // 创建档案
                    db.collection('friends').update({ "userid": user._id },
                        {
                            $set: { 'list': _updateList }
                        }, function (err, result) {

                            if (err) {
                                callback({ success: false, error: '更新frinds表失败', msg: '更新失败' });
                            } else {
                                callback({ success: true, data: result });
                            }
                            db.close();

                        });

                } else {

                    let _list = [];

                    _list.push(friend);

                    console.log('插入数据');

                    console.log(_list);

                    // 创建档案
                    db.collection('friends').insertOne({
                        "list": _list,
                        "username": user.username,
                        "userid": user._id,
                        "createtime": friend.createtime
                    }, function (err, result) {

                        if (err) {
                            callback({ success: false, error: '插入frinds表失败', msg: '添加好友失败' });
                        } else {
                            console.log('success');
                            callback({ success: true, data: result });
                        }
                        db.close();
                    });
                }
            }
        });

    });
};

module.exports = user;